package com.itext.sample;

import java.awt.FontMetrics;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.swing.JLabel;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;


public class PDFWaterPrint {

    // 间隔
    public final static int interval = -new Random().nextInt(20) * 7;

    public static void main(String[] args) throws Exception {

        // 将pdf文件先加水印然后输出
        setWatermark("d:/temp/noApprove-2.pdf",
                "d:/temp/noApprove-2" + interval + ".pdf",
                getWaterMake() + "生成");
    }

    public static String getWaterMake() {
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        return sdf.format(date)+ "生成";
    }


    /**
     * @param sourceFile    源PDF
     * @param targetFile    目标PDF
     * @param waterMarkName 页脚添加水印
     * @throws DocumentException
     * @throws IOException
     */
    public static void setWatermark(String sourceFile, String targetFile, String waterMarkName) throws Exception {

        // 要输出的pdf文件
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(targetFile)));

        PdfReader reader = new PdfReader(sourceFile);
        PdfStamper stamper = new PdfStamper(reader, bos);

        // 获取总页数 +1, 下面从1开始遍历
        int total = reader.getNumberOfPages() + 1;
        BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        // 使用classpath下面的字体库
        /*
        BaseFont base = null;
        try {
            base = BaseFont.createFont("/calibri.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (Exception e) {
            // 日志处理
            e.printStackTrace();
        }
        */


        System.out.println("Random interval: " + interval);

        // 获取水印文字的高度和宽度
        int textH = 0, textW = 0;
        JLabel label = new JLabel();
        label.setText(waterMarkName);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        textH = metrics.getHeight();
        textW = metrics.stringWidth(label.getText());
        System.out.println("textH: " + textH);
        System.out.println("textW: " + textW);

        // 设置水印透明度
        PdfGState gs = new PdfGState();

        // 填充透明度
        gs.setFillOpacity(0.2f);
        // 边框透明度
        gs.setStrokeOpacity(0.4f);

        Rectangle pageSizeWithRotation = null;
        PdfContentByte content = null;
        // 遍历页码
        for (int i = 1; i < total; i++) {
            // 在内容上方加水印
            content = stamper.getOverContent(i);
            // 在内容下方加水印
            // content = stamper.getUnderContent(i);
            content.saveState();
            content.setGState(gs);

            // 设置字体和字体大小
            content.beginText();
            content.setFontAndSize(base, 12);

            // 获取每一页的高度、宽度
            pageSizeWithRotation = reader.getPageSizeWithRotation(i);
            float pageHeight = pageSizeWithRotation.getHeight();
            float pageWidth = pageSizeWithRotation.getWidth();

            int stepW = textW * 2,
                    stepH = textH * 5,
                    countW = Math.round(pageWidth / stepW),
                    countH = Math.round(pageHeight / stepH);
            float rotation = textW / textH;
//            rotation = stepW / stepH;


            System.out.println("pageHeight: " + pageHeight);
            System.out.println("pageWidth: " + pageWidth);
            System.out.println("countW: " + countW);
            System.out.println("countH: " + countH);
            System.out.println("rotation text: " + textW / textH);
            System.out.println("rotation step: " + stepW / stepH);


            for (int indexH = 0; indexH < countH; indexH++) {
                float x = (interval + textW * indexH) % pageWidth,
                        y = interval + stepH * indexH;

                for (int indexW = 0; indexW < countW; indexW++) {
                    x = x + stepW * indexW;
                    if (x > pageWidth) {
                        x = pageWidth - x;
                    }
                    content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, x, y, rotation);
                    System.out.println(indexH + "\tx : " + x + "\ty : " + y);
                }

            }

/*

            // 根据纸张大小多次添加， 水印文字成30度角倾斜
            int index = 1;
            System.out.println("begin x :" + (float) (index * textW));
            for (int height = interval + textH; height < pageHeight; height = height + textH * 4) {
                float x = Math.abs(pageWidth - (float) (index * textW)),
                        y = height - textH;
                content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, x, y, 30);

                System.out.println(index + "\tx : " + x + "\ty : " + y);

                for (int width = interval + textW * index; width < pageWidth + textW; width = width + textW * 2) {
                    System.out.println(index +
                            "\theight : " + height +
                            "\twidth : " + width +
                            "\tx : " + (width - textW) +
                            "\ty : " + (height - textH));
                    content.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 30);
                }
                index++;
            }
*/

            content.endText();
        }

        // 关流
        stamper.close();
        reader.close();
        bos.close();
    }

}
